package cn.com.weshare.lock.jmm;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author dujunguang
 * @description: TODO
 * @date: 2022/9/4 22:20
 * @version: 1.0.0
 **/
public class IPlusPlus {

    public static void main(String[] args) {
        CountDownLatch cdl = new CountDownLatch(100000);
        Resource resource = new Resource();
//        // 单线程i++
//        for (int i = 0; i < 100000; i++) {
//            resource.plus();
//        }
//        resource.print();
        // 多线程i++
        for (int j = 0; j < 100000; j++) {
            new Thread(() -> {
                resource.plus();
                cdl.countDown();
            }, "Thread").start();
        }

        // JUC CAS无锁实现原子性
//        for (int i = 0; i < 100000; i++) {
//            new Thread(() -> {
//                resource.app();
//                cdl.countDown();
//            }, "Thread").start();
//        }
//        try {
//            TimeUnit.SECONDS.sleep(5);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        resource.print();
//        resource.printa();

    }

}

class Resource{
    public int num = 0;

    public AtomicInteger a = new AtomicInteger(0);

    public synchronized void plus() {
        num++;
    }

    public void app() {
        a.incrementAndGet();
    }

    public void print() {
        System.out.println(num);
    }

    public void printa() {
        System.out.println(a.get());
    }
}


